import { access, readFile, writeFile, constants } from 'fs/promises';
import { setFilePath } from '../../../utils/index.js';
import { user } from '../../../config/auth/index.js'

const usersFilePath = setFilePath(2, user.userInfonDbPath);
const passwordFilePath = setFilePath(2, user.userPasswordDbPath);

// 检查文件是否存在
const checkFileExists = async (filePath) => {
    try {
        await access(filePath, constants.F_OK);
        return true;
    } catch {
        return false;
    }
};

// 初始化用户数据文件
const initUsersFile = async () => {
    try {
        const fileExists = await checkFileExists(usersFilePath);
        if (!fileExists) {
            await writeFile(usersFilePath, JSON.stringify([], null, 2));
            console.log('用户数据文件已创建:', usersFilePath);
        }
        await initPasswordsFile(); // 初始化密码文件
    } catch (error) {
        console.error('初始化用户数据文件失败:', error);
    }
};

// 初始化密码文件
const initPasswordsFile = async () => {
    try {
        const fileExists = await checkFileExists(passwordFilePath);
        if (!fileExists) {
            await writeFile(passwordFilePath, JSON.stringify([], null, 2));
            console.log('密码数据文件已创建:', passwordFilePath);
        }
    } catch (error) {
        console.error('初始化密码数据文件失败:', error);
    }
};

// 读取用户数据
const getUsers = async () => {
    try {
        await initUsersFile(); // 确保文件存在
        const data = await readFile(usersFilePath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error('读取用户数据失败:', error);
        return [];
    }
};

// 写入用户数据
const setUsers = async (users) => {
    try {
        await writeFile(usersFilePath, JSON.stringify(users, null, 2));
    } catch (error) {
        console.error('写入用户数据失败:', error);
    }
};

// 读取密码数据
const getPasswords = async () => {
    try {
        await initPasswordsFile(); // 确保文件存在
        const data = await readFile(passwordFilePath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error('读取密码数据失败:', error);
        return [];
    }
};

// 写入密码数据
const setPasswords = async (passwords) => {
    try {
        await writeFile(passwordFilePath, JSON.stringify(passwords, null, 2));
    } catch (error) {
        console.error('写入密码数据失败:', error);
    }
};

// 添加用户
const addUser = async (username, password) => {
    try {
        const users = await getUsers();
        const passwords = await getPasswords();

        const userExists = users.some((user) => user.username === username);
        if (userExists) {
            throw new Error('用户名已存在');
        }

        users.push({ username });
        await setUsers(users);

        passwords.push({ username, password });
        await setPasswords(passwords);

        console.log('用户添加成功:', username);
    } catch (error) {
        console.error('添加用户失败:', error.message);
    }
};

// 查找用户
const findUser = async (username) => {
    try {
        const users = await getUsers();
        return users.find((user) => user.username === username);
    } catch (error) {
        console.error('查找用户失败:', error);
        return null;
    }
};

// 验证用户
const validateUser = async (username, password) => {
    try {
        const passwords = await getPasswords();
        const userPassword = passwords.find((p) => p.username === username);

        if (!userPassword) {
            throw new Error('用户不存在');
        }
        if (userPassword.password !== password) {
            throw new Error('密码错误');
        }
        return true;
    } catch (error) {
        console.error('验证用户失败:', error.message);
        return false;
    }
};

// 删除用户
const deleteUser = async (username) => {
    try {
        const users = await getUsers();
        const passwords = await getPasswords();

        const updatedUsers = users.filter((user) => user.username !== username);
        if (users.length === updatedUsers.length) {
            throw new Error('用户不存在');
        }
        await setUsers(updatedUsers);

        const updatedPasswords = passwords.filter((p) => p.username !== username);
        await setPasswords(updatedPasswords);

        console.log('用户删除成功:', username);
    } catch (error) {
        console.error('删除用户失败:', error.message);
    }
};

export { getUsers, setUsers, addUser, findUser, validateUser, deleteUser };